package com.hmkj.web.controller.follow;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.page.BasePageParams;
import com.hmkj.common.page.Pages;
import com.hmkj.core.constant.ConfigNID;
import com.hmkj.core.constant.RiskNID;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.mapper.follow.FollowRuleMapper;
import com.hmkj.core.mapper.order.OrderSimulateMapper;
import com.hmkj.core.model.follow.FollowRuleModel;
import com.hmkj.core.model.order.OrderSimulateModel;
import com.hmkj.core.po.commo.Commo;
import com.hmkj.core.po.follow.FollowRule;
import com.hmkj.core.po.operate.Agent;
import com.hmkj.core.po.order.Order;
import com.hmkj.core.po.order.OrderSimulate;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.commo.CommoService;
import com.hmkj.core.service.follow.FollowRuleService;
import com.hmkj.core.service.investor.InvestorService;
import com.hmkj.core.service.operate.AgentService;
import com.hmkj.core.service.order.OrderService;
import com.hmkj.core.service.order.OrderSimulateService;
import com.hmkj.core.service.risk.RiskParamService;
import com.hmkj.core.service.user.UserService;
import com.hmkj.web.controller.GenericController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Api(description = "跟单相关")
@Slf4j
@RestController
@RequestMapping(GenericController.MEMBER_URL + "/follow")
public class FollowRuleController extends GenericController<Integer, FollowRule> {

    @Resource
    private FollowRuleService followRuleService;
    @Resource
    private OrderSimulateService orderSimulateService;
    @Resource
    private AgentService agentService;
    @Resource
    private RiskParamService riskParamService;
    @Resource
    private CommoService commoService;
    @Resource
    private OrderService orderService;
    @Resource
    private UserService userService;
    @Resource
    private InvestorService investorService;

    /**
     * 查看战绩
     *
     * @return
     */
    @ApiOperation(value = "获取战绩", notes = "获取战绩")
    @ResponseBody
    @RequestMapping(value = "getRecord", method = RequestMethod.POST)
    public ResultEntity<Pages<OrderSimulateModel>> getRecord(@ApiParam("操盘人id") @RequestParam(required = true) Integer id, @ModelAttribute BasePageParams basePageParams) {
        Map<String, Object> param = new HashMap<>();
        String domain = getDomain();
        Agent agent = agentService.selectAgentByDomain(domain);
        if (agent != null) {
            param.put("agentId", agent.getId());
        } else {
            param.put("agentId", "");
        }
        param.put("userId", id);
        param.put("status", OrderSimulate.STATUS.T6.code);
        param.put("delFlag", OrderSimulate.DELFLAG.NORMAL.code);
        param.put("basePageParams", basePageParams);
        Pages<OrderSimulateModel> pages = orderSimulateService.selectByPage(basePageParams,
                p -> ((OrderSimulateMapper) p).findCountByUserId(param),
                p -> ((OrderSimulateMapper) p).findListByUserId(param));
        List<OrderSimulateModel> models = pages.getRows();
        if (models != null && models.size() > 0) {
            models.forEach(orderSimulateModel -> {
                BigDecimal exchangeRate = riskParamService.getParamValue(RiskNID.EXCHANGE_RATE, orderSimulateModel.getCommoId(), BigDecimal.class);//汇率
                orderSimulateModel.setExchangeRate(exchangeRate);
            });
        }
        pages.setRows(models);
        return ok(pages);
    }

    /**
     * 跟单列表
     */
    @ApiOperation(value = "跟单列表", notes = "跟单列表")
    @ResponseBody
    @RequestMapping(value = "getList", method = RequestMethod.POST)
    public ResultEntity<Pages<OrderSimulateModel>> getList(@ModelAttribute BasePageParams basePageParams) {
        Map<String, Object> param = new HashMap<>();
        String domain = getDomain();
        Agent agent = agentService.selectAgentByDomain(domain);
        if (agent != null) {
            param.put("agentId", agent.getId());
        } else {
            param.put("agentId", "");
        }
        param.put("status", OrderSimulate.STATUS.T6.code);
        param.put("delFlag", OrderSimulate.DELFLAG.NORMAL.code);
        param.put("type", User.TYPE.T3.code);
        param.put("basePageParams", basePageParams);
        Pages<OrderSimulateModel> pages = orderSimulateService.selectByPage(basePageParams,
                p -> ((OrderSimulateMapper) p).findCountForOrderSimList(param),
                p -> ((OrderSimulateMapper) p).findListForOrderSimList(param));
        List<OrderSimulateModel> models = pages.getRows();
        if (models != null && models.size() > 0) {
            models.forEach(orderSimulateModel -> {
                orderSimulateModel.setFollowNum(followRuleService.selcetCountByFollowId(orderSimulateModel.getUserId()));
            });
        }
        pages.setRows(models);
        return ok(pages);
    }

    /**
     * 确认跟单页显示数据
     */
    @ApiOperation(value = "确认跟单页显示数据", notes = "确认跟单页显示数据")
    @ResponseBody
    @RequestMapping(value = "followOrderShow", method = RequestMethod.POST)
    public ResultEntity followOrderShow() {
        String followHandNum = redisService.get(ConfigNID.FOLLOW_HAND_NUM);
        String followMax = redisService.get(ConfigNID.FOLLOW_HAND_MAX);
        List<Integer> list = new ArrayList<>();
        String[] vals = followHandNum.split(",");
        for (String val : vals) {
            list.add(Integer.parseInt(val));
        }
        //默认美黄金跟单综合服务费
        Commo commo = commoService.selectOne(new Commo(c -> {
            c.setCode("GC");
            c.setDelFlag(Commo.DELFLAG.NORMAL.code);
        }));
        Integer fee = riskParamService.getParamValue(RiskNID.FOLLOW_FEE, 1, Integer.class);
        BigDecimal allotRate = riskParamService.getParamValue(RiskNID.ALLOT_RATE, commo.getId(), BigDecimal.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("followHandNum", list);//跟单手数
        map.put("fee", fee);
        map.put("allotRate", allotRate);
        map.put("followMax", followMax);
        return ok(map);
    }


    /**
     * do确认跟单
     */
    @ApiOperation(value = "确认跟单", notes = "确认跟单")
    @ResponseBody
    @RequestMapping(value = "doFollowOrder", method = RequestMethod.POST)
    public ResultEntity doFollowOrder(@ApiParam("操盘人id") @RequestParam(required = true) Integer followId, @ApiParam("跟单手数") @RequestParam(required = true) Integer num) {
        User user = getLoginUser();
        User trader = userService.selectByPrimaryKey(followId);
        if(null == trader || trader.getType() != User.TYPE.T3.code){
            throw new BussinessException("操盘手身份错误");
        }
        List<FollowRule> rules = followRuleService.select(new FollowRule( fr->{
            fr.setUserId(user.getId());
            fr.setStatus(FollowRule.STATUS.T1.code);
            fr.setFollowId(followId);
            fr.setDelFlag(FollowRule.DELFLAG.NORMAL.code);
        }));
        if(rules!=null&&rules.size()>0){
            throw new BussinessException("已对当前用户跟单");
        }
        FollowRule followRule = new FollowRule();
        String domain = getDomain();
        if (num != null && num > 0) {
            followRule.setNumber(num);
        } else {
            throw new BussinessException("参数有误");
        }
        followRule.setFollowId(followId);
        followRule.setUserId(user.getId());
        followRule.setStatus(FollowRule.STATUS.T1.code);
        followRule.setDomain(domain);
        followRule.setDelFlag(FollowRule.DELFLAG.NORMAL.code);
        followRule.setCreateTime(new Date());
        followRuleService.insert(followRule);
        return ok();
    }

    /**
     * 我的跟单
     */
    @ApiOperation(value = "我的跟单", notes = "我的跟单")
    @ResponseBody
    @RequestMapping(value = "myFollowOrder", method = RequestMethod.POST)
    public ResultEntity<Pages<FollowRuleModel>> myFollowOrder(@ModelAttribute BasePageParams basePageParams) {
        Map<String, Object> param = new HashMap<>();
        User user = getLoginUser();
        param.put("status", FollowRule.STATUS.T1.code);
        param.put("userId", user.getId());
        param.put("delFlag", FollowRule.DELFLAG.NORMAL.code);
        param.put("basePageParams", basePageParams);
        Pages<FollowRuleModel> pages = followRuleService.selectByPage(basePageParams,
                p -> ((FollowRuleMapper) p).findCountForFollowRuleList(param),
                p -> ((FollowRuleMapper) p).findListForFollowRuleList(param));

        List<FollowRuleModel> models = pages.getRows();
        //默认美黄金
        Commo commo = commoService.selectOne(new Commo(c -> {
            c.setCode("GC");
            c.setDelFlag(Commo.DELFLAG.NORMAL.code);
        }));
        BigDecimal pointVlaue = riskParamService.getParamValue(RiskNID.POINT_VALUE, commo.getId(), BigDecimal.class);//每点合约价格
        List<Integer> lostStopPoints = riskParamService.getParam2IntList(RiskNID.LOSE_STOP_POINT, commo.getId());// 止损点数列表
        BigDecimal exchangeRate = riskParamService.getParamValue(RiskNID.EXCHANGE_RATE, commo.getId(), BigDecimal.class);//汇率
        BigDecimal loseStopRate = riskParamService.getParamValue(RiskNID.LOSE_STOP_RATE, commo.getId(), BigDecimal.class); // 止损比例
        BigDecimal fee = riskParamService.getFeeByAgent(commo.getId(), user.getAgentId());// 每手手续费
        Integer lostStopPoint = null;
        if (lostStopPoints != null && lostStopPoints.size() > 0) {
            for (Integer lp : lostStopPoints) {
                if (lostStopPoint == null) {
                    lostStopPoint = lp;
                } else {
                    if (lostStopPoint > lp) {
                        lostStopPoint = lp;
                    }
                }
            }
        } else {
            throw new BussinessException("系统参数有误");
        }
        if (models != null && models.size() > 0) {
            Integer finalLostStopPoint = lostStopPoint;
            models.forEach(followRuleModel -> {
                //占用资金 = (每点价值*止损点数（最小）*汇率*手数)/止损比例
                followRuleModel.setNeedAmount(pointVlaue.multiply(BigDecimal.valueOf(finalLostStopPoint)).multiply(exchangeRate).multiply(BigDecimal.valueOf(followRuleModel.getNumber())).divide(loseStopRate).add(fee));
            });
        }
        pages.setRows(models);
        return ok(pages);
    }


    /**
     * 取消跟单
     */
    @ApiOperation(value = "取消跟单", notes = "取消跟单")
    @ResponseBody
    @RequestMapping(value = "cancelFollow", method = RequestMethod.POST)
    public ResultEntity cancelFollow(@ApiParam("操盘人id") @RequestParam(required = true) Integer followId) {
        User user = getLoginUser();

        List<FollowRule> rules = followRuleService.select(new FollowRule( fr->{
            fr.setUserId(user.getId());
            fr.setStatus(FollowRule.STATUS.T1.code);
            fr.setFollowId(followId);
            fr.setDelFlag(FollowRule.DELFLAG.NORMAL.code);
        }));
        if(CollectionUtils.isNotEmpty(rules)){
            FollowRule rule = rules.get(0);
            followRuleService.updateByPrimaryKeySelective(new FollowRule( followRule->{
                followRule.setId(rule.getId());
                followRule.setStatus(FollowRule.STATUS.T2.code);
                }));
        }else {
            throw new BussinessException("跟单不存在");
        }
        return ok();
    }

    /**
     * 合同详情
     */
    @ApiOperation(value = "合同详情", notes = "合同详情")
    @ResponseBody
    @RequestMapping(value = "contractDetail", method = RequestMethod.POST)
    public ResultEntity contractDetail(@ApiParam("订单id") @RequestParam(required = true) Integer orderId) {
        if(null==orderId){
            throw new BussinessException("参数有误");
        }
        Order order = orderService.selectByPrimaryKey(orderId);
        if(null==order){
            throw new BussinessException("订单不存在");
        }
        User user = userService.selectByPrimaryKey(order.getUserId());
        String userName = "";
        if(user.getRealName()!=null){
           userName  = user.getRealName().substring(0,user.getRealName().length()-1)+"*";
        }
//        Investor investor =  investorService.selectByPrimaryKey(order.getInvestId());
        User invUser = userService.selectByPrimaryKey(order.getInvestId());
        String investName = "";
        if(invUser.getRealName()!=null){
            investName  = invUser.getRealName().substring(0,invUser.getRealName().length()-1)+"*";
        }
        Map<String,Object> map = new HashMap<>();
        map.put("userId",order.getUserId());
        map.put("userName",userName);
        map.put("investId",order.getInvestId());
        map.put("investName",investName);
        map.put("commoName",order.getName());
        map.put("direction",order.getDirectionFormatter());
        map.put("numer",order.getNumber());
        map.put("profitStopPrice",order.getProfitStopPrice());
        map.put("loseStopPrice",order.getLoseStopPrice());
        map.put("code",order.getCode());
        Agent agent = agentService.selectByPrimaryKey(order.getAgentId());
        if (null==agent){
            throw new BussinessException("代理商信息有误");
        }
        map.put("fullName",agent.getFullName());
        return ok(map);
    }

}
